﻿<%@ LANGUAGE="JSCRIPT" %>
<!--#include file ="Includes/DB.asp"--> <!-- Namespace: DB -->
<!--#include file ="Includes/JSON2.asp"-->
<!--#include file ="Includes/ASPHelpers.asp"--> <!-- Namespace: Helpers -->

<%
	var fileName = String(Request.QueryString("filename") || "not found");

	var Success = "true";	/* have to do this weird boolean string thing because for some reason when I try to assign a server-side boolean 
							 * to a client-side variable (as is the case in the final response of this page down at the bottom)
							 * it comes out Proper-case True/False which causes client-side JS to throw an error saying "True/False is not defined" */
	var ErrorMsg = "";
	var script = {};
	var fs
		, filepath
		, file
		, fileContent = "";
	var db
		,rs;


	/*-------------------------------------------------------*/
	try{
		
		/*-------------------------------------------------------*/
		/* GET FILE */
		fs = Server.CreateObject("scripting.filesystemobject");
		filepath = Server.MapPath("TempScriptImport/" + fileName);
		
		if(!fs.FileExists(filepath)){
			throw "Script file '" + fileName + "' not found.";	
		}
		
		file = fs.OpenTextFile(filepath, 1, false, -2);
		fileContent = file.ReadAll();
		file.Close();


		/*-------------------------------------------------------*/
		/* DESERIALIZE */
		try{
			script = JSON.parse(fileContent);
		}
		catch(e)
		{
			throw "Failed To DeSerialize";
		}

		
		/*-------------------------------------------------------*/
		/* TEST SCRIPT OBJECT */
		if(!script.ScriptID
			|| !script.Category 
			|| !script.Title
			|| !script.Created)
		{
			throw "Missing Primary Script Properties";
		}

		if(!script.scriptBlocks){
			throw "Missing Script Blocks";
		}

		if(!script.decisions){
			throw "Missing Decisions";
		}



		/*-------------------------------------------------------*/
		/* CREATE DB OBJECT */
		db = new DB.DataCall();
		db.ManualCloseConnection =	true;
		db.ConnectionString = 		DB.ConnectionStrings.Scripts;
		db.CommandType = 			DB.CommandTypes.StoredProc;



		/*-------------------------------------------------------*/
		/* LOOK FOR SCRIPT ID IN DB */
		db.QueryName =	"qryGetScript";
			
		db.AddParameter("@ScriptID", DB.DataTypes.String, script.ScriptID);
			
		db.Execute();

		if(!db.Success){
			throw "Search Script(" + script.ScriptID + "): " + db.ErrorMessage;
		}


		/*-------------------------------------------------------*/
		/* IF FOUND THEN EDIT ELSE ADD NEW */
		rs = db.RecordSet;

		if(rs.RecordCount > 0){/* edit */
			db.Parameters = [];
			db.QueryName =	"qryImport_UpdateScript";

			db.AddParameter("@ScriptID", DB.DataTypes.String, script.ScriptID);
			db.AddParameter("@Category", DB.DataTypes.String, script.Category);
			db.AddParameter("@Title", DB.DataTypes.String, script.Title);
			db.AddParameter("@Modified", DB.DataTypes.String, Helpers.ToDateTimeString(script.Modified, "MM/dd/yyyy hh:mm:ss") );
			db.AddParameter("@ModifiedBy", DB.DataTypes.String, script.ModifiedBy);
			
//			var sql = Helpers.StringFormat("UPDATE tblScripts SET Category='{0}', Title='{1}', Modified=#{2}#, ModifiedBy='{3}' WHERE ScriptID='{4}'"
//						,[	
//							script.Category
//							, script.Title
//							, Helpers.ToDateTimeString(script.Modified, "MM/dd/yyyy hh:mm:ss")
//							, script.ModifiedBy
//							, script.ScriptID
//						]);

//			throw sql;
//			db.SQL = sql;

			db.Execute();

			if(!db.Success){
				throw "Update Script(" + script.ScriptID + "): " + db.ErrorMessage;
			}
		}
		else {/* add New */
			db.Parameters = [];
			db.QueryName =	"qryImport_InsertScript";

			db.AddParameter("@ScriptID", DB.DataTypes.String, script.ScriptID);
			db.AddParameter("@Category", DB.DataTypes.String, script.Category);
			db.AddParameter("@Title", DB.DataTypes.String, script.Title);
			db.AddParameter("@Created", DB.DataTypes.String, Helpers.ToDateTimeString(script.Created, "MM/dd/yyyy hh:mm:ss") );
			db.AddParameter("@CreatedBy", DB.DataTypes.String, script.CreatedBy);

			db.Execute();

			if(!db.Success){
				throw "Insert Script(" + script.ScriptID + "): " + db.ErrorMessage;
			}
		}


		/*-------------------------------------------------------*/
		/* ITERATE SCRIPTBLOCKS */
		for(var x = 0; x < script.scriptBlocks.length; x++)
		{
			var curScriptBlock = script.scriptBlocks[x];

			/* LOOK FOR SCRIPTBLOCK ID IN DB */
			db.Parameters = [];
			db.QueryName =	"qryGetScriptBlockByScriptBlockID";
			
			db.AddParameter("@ScriptBlockID", DB.DataTypes.String, curScriptBlock.ScriptBlockID);
			
			db.Execute();

			if(!db.Success){
				throw "Search ScriptBlock(" + curScriptBlock.ScriptBlockID + "): " + db.ErrorMessage;
			}

			/*-------------------------------------------------------*/
			/* IF FOUND THEN EDIT ELSE ADD NEW */
			if(db.RecordSet.RecordCount > 0){/* edit */
				db.Parameters = [];
				db.QueryName =	"qryImport_UpdateScriptBlock";

				db.AddParameter("@ScriptBlockID", DB.DataTypes.String, curScriptBlock.ScriptBlockID);
				db.AddParameter("@ScriptID", DB.DataTypes.String, curScriptBlock.ScriptID);
				db.AddParameter("@DecisionID", DB.DataTypes.String, curScriptBlock.DecisionID);
				db.AddParameter("@ScriptText", DB.DataTypes.String, curScriptBlock.ScriptText);
				db.AddParameter("@Modified", DB.DataTypes.String, Helpers.ToDateTimeString(curScriptBlock.Modified, "MM/dd/yyyy hh:mm:ss") );
				db.AddParameter("@ModifiedBy", DB.DataTypes.String, curScriptBlock.ModifiedBy);
			
				db.Execute();

				if(!db.Success){
					throw "Update ScriptBlock(" + curScriptBlock.ScriptBlockID + "): " + db.ErrorMessage;
				}
			}
			else {/* add New */
				db.Parameters = [];
				db.QueryName =	"qryImport_InsertScriptBlock";

				db.AddParameter("@ScriptBlockID", DB.DataTypes.String, curScriptBlock.ScriptBlockID);
				db.AddParameter("@ScriptID", DB.DataTypes.String, curScriptBlock.ScriptID);
				db.AddParameter("@DecisionID", DB.DataTypes.String, curScriptBlock.DecisionID);
				db.AddParameter("@ScriptText", DB.DataTypes.String, curScriptBlock.ScriptText);
				db.AddParameter("@Created", DB.DataTypes.String, Helpers.ToDateTimeString(curScriptBlock.Created, "MM/dd/yyyy hh:mm:ss") );
				db.AddParameter("@CreatedBy", DB.DataTypes.String, curScriptBlock.CreatedBy);

				db.Execute();

				if(!db.Success){
					throw "Insert ScriptBlock(" + curScriptBlock.ScriptBlockID + "): " + db.ErrorMessage;
				}

			}

		}//next scriptBlock


		/*-------------------------------------------------------*/
		/* ITERATE DECISIONS */
		for(var x = 0; x < script.decisions.length; x++)
		{
			var curDecision = script.decisions[x];


			/*-------------------------------------------------------*/
			/* LOOK FOR DECISION IN DB */
			db.Parameters = [];
			db.QueryName =	"qryGetDecisionByDecisionID";
			
			db.AddParameter("@DecisionID", DB.DataTypes.String, curDecision.DecisionID);
			
			db.Execute();

			if(!db.Success){
				throw "Search Decision(" + curDecision.DecisionID + ")" + db.ErrorMessage;
			}


			/*-------------------------------------------------------*/
			/* IF FOUND THEN EDIT ELSE ADD NEW */
			if(db.RecordSet.RecordCount > 0){/* edit */
				db.Parameters = [];
				db.QueryName =	"qryImport_UpdateDecision";

				db.AddParameter("@DecisionID", DB.DataTypes.String, curDecision.DecisionID);
				db.AddParameter("@ScriptID", DB.DataTypes.String, curDecision.ScriptID);
				db.AddParameter("@ScriptBlockID", DB.DataTypes.String, curDecision.ScriptBlockID);
				db.AddParameter("@DecisionTitle", DB.DataTypes.String, curDecision.DecisionTitle);
				db.AddParameter("@Order", DB.DataTypes.String, curDecision.Order);
				db.AddParameter("@Modified", DB.DataTypes.String, Helpers.ToDateTimeString(curDecision.Modified, "MM/dd/yyyy hh:mm:ss") );
				db.AddParameter("@ModifiedBy", DB.DataTypes.String, curDecision.ModifiedBy);
			
				db.Execute();

				if(!db.Success){
					throw "Update Decision(" + curDecision.DecisionID + "): " + db.ErrorMessage;
				}
			}
			else {/* add New */
				db.Parameters = [];
				db.QueryName =	"qryImport_InsertDecision";

				db.AddParameter("@DecisionID", DB.DataTypes.String, curDecision.DecisionID);
				db.AddParameter("@ScriptID", DB.DataTypes.String, curDecision.ScriptID);
				db.AddParameter("@ScriptBlockID", DB.DataTypes.String, curDecision.ScriptBlockID);
				db.AddParameter("@DecisionTitle", DB.DataTypes.String, curDecision.DecisionTitle);
				db.AddParameter("@Order", DB.DataTypes.String, curDecision.Order);
				db.AddParameter("@Created", DB.DataTypes.String, Helpers.ToDateTimeString(curDecision.Created, "MM/dd/yyyy hh:mm:ss") );
				db.AddParameter("@CreatedBy", DB.DataTypes.String, curDecision.CreatedBy);

				db.Execute();

				if(!db.Success){
					throw "Insert Decision(" + curDecision.DecisionID + "): " + db.ErrorMessage;
				}

			}

		}//next decision


		/*-------------------------------------------------------*/
		/* CLEAN UP */
		if(db.Connection.State == 1){
			db.Connection.Close();
			db.Connection = null;
		}

	}
	catch(e){
		Success = "false"; //see top for reason why this is string
		ErrorMsg = e;
	}
	finally{
		%>
			<html>
				<head>
					<script type='text/javascript'>
						var ret = {};
						ret.FileName ="<%= fileName %>";
						ret.Success = <%= Success %>;
						ret.ErrorMsg = "<%= ErrorMsg.replace(/\n/g,"\\n") %>";

						parent.AdminScriptEditor.ImportDialogOnComplete(ret);
					</script>
		

				</head>
				<body>

			</body>
			</html>
		<%
	}
%>


